package com.mindskip.gushuang.qrCraft;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.mindskip.gushuang.base.RestResponse;
import com.mindskip.gushuang.service.FileUpload;
import com.mindskip.gushuang.utility.ImageToInputStream;
import com.mindskip.gushuang.utility.MinioUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 孤霜
 * @version 1.0
 */
@Controller
@ResponseBody
public class QrCraft {

    @Value("${server.port}")
    private String port;

    @Resource
    private MinioUtil minioUtil;

    @Resource
    FileUpload fileUpload;


    @GetMapping("/qr")
    public RestResponse qr(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        try {
            String userId = httpServletRequest.getParameter("id");
            Map map = new HashMap<>();
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");
            map.put(EncodeHintType.MARGIN, 1);
            MultiFormatWriter writer = new MultiFormatWriter();
            String ip = null;
            try {
                InetAddress inetAddress = InetAddress.getLocalHost();
                ip = inetAddress.getHostAddress();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            String url = "http://" + ip + ":" + port + "/updateImg.html?userId=" + userId;
            BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, 300, 300, map);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }
            ByteArrayInputStream imageInputStream = ImageToInputStream.bufferImageToInputStream(image);
            // todo
            String imgUrl = fileUpload.uploadFile(imageInputStream, 10, "zzz.png");
            return RestResponse.ok(imgUrl);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RestResponse.fail(404,"二维码产生错误");
    }


    @PostMapping("/myqrcode/generateWithLogo")
    public void generateWithLogo(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse
    ) {
        try {
            String url = httpServletRequest.getParameter("url");
            Map map = new HashMap<>();
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            map.put(EncodeHintType.CHARACTER_SET, "utf-8");
            map.put(EncodeHintType.MARGIN, 1);
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, 300, 300, map);
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }

            Part logoPart = httpServletRequest.getPart("logo");
            InputStream inputStream = logoPart.getInputStream();
            Image logoImage = ImageIO.read(inputStream);
            int logoWidth = logoImage.getWidth(null);
            int logoHeight = logoImage.getHeight(null);
            if (logoWidth > 60) {
                logoWidth = 60;
            }
            if (logoHeight > 60) {
                logoHeight = 60;
            }
            Image scaledLogo = logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH);
            Graphics2D graphics = image.createGraphics();
            int x = (300 - logoWidth) / 2;
            int y = (300 - logoHeight) / 2;
            graphics.drawImage(scaledLogo, x, y, null);
            Shape shape = new RoundRectangle2D.Float(x, y, logoWidth, logoHeight, 10, 10);
            graphics.setStroke(new BasicStroke(4f));
            graphics.draw(shape);
            graphics.dispose();
            ServletOutputStream out = httpServletResponse.getOutputStream();
            ImageIO.write(image, "png", httpServletResponse.getOutputStream());
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }


}
